package com.dailyblue.java.project.smbms.stock.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.java.project.smbms.stock.bean.Stock;
import com.dailyblue.java.project.smbms.stock.mapper.StockMapper;
import com.dailyblue.java.project.smbms.stock.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

@Service
@Slf4j
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements StockService {
    @Resource
    private StockMapper stockMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //@Resource
    //private RocketMQTemplate rocketMQTemplate;

    // @Cacheable(cacheNames = "findStockById", key = "#id")
    public Stock getById(Serializable id) {
        HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
        // 查看缓存中是否存在对应id的数据
        String value = hash.get("STOCK_ID", id + "");
        if (value == null) {
            // Redis中没有这条记录，需要查询数据库
            Stock stock = stockMapper.findStockById(id);
            // 存放到Redis中
            hash.put("STOCK_ID", id + "", JSONArray.toJSONString(stock));
            return stock;
        }
        return JSONArray.parseObject(value, Stock.class);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int updateStockNum(int bid, int num) throws SQLException {
        // 更新数据库的数据
        int count = stockMapper.updateStockNum(bid, num);
        // 更新Redis的数据
        if (count > 0) {
            HashOperations<String, String, String> hash = stringRedisTemplate.opsForHash();
            String value = hash.get("STOCK_ID", bid + "");
            Stock stock = JSONArray.parseObject(value, Stock.class);
            int newNum = stock.getNum() + num;
            stock.setNum(newNum);
            hash.put("STOCK_ID", bid + "", JSONArray.toJSONString(stock));
        }
        // 生产了一笔消息存放到RocketMQ中
        /*int type = num > 0 ? 1 : 2; // 1:入库 2:出库
        int num1 = num > 0 ? num : 0 - num;
        String body = "{\"uid\":\"1\",\"gid\":\"" + bid + "\",\"type\":\"" + type + "\",\"num\":\"" + num1 + "\"}";
        SendResult result = rocketMQTemplate.syncSend("STOCK:LOG", body);
        log.info("ROCKET_MQ：{}", result);*/
        return count;
    }
}
